package com.seesmic.methodgroups
{
	/*
	Copyright 2007 SEESMIC, Inc
	Licensed under the Apache License, Version 2.0 (the "License"); 
	you may not use this file except in compliance with the License. You may obtain a copy of the License at 
	
	http://www.apache.org/licenses/LICENSE-2.0 
	
	Unless required by applicable law or agreed to in writing, 
	software distributed under the License is distributed on an 
	"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
	See the License for the specific language governing permissions and limitations under the License.
	*/
	
	import com.adobe.crypto.MD5;
	import com.seesmic.SeesmicService;
	import com.seesmic.ServiceBase;
	import com.seesmic.events.SeesmicResultEvent;
	import com.serialization.json.JSON;
	
	import flash.events.Event;
	import flash.net.URLLoader;
	
	 
	public class Auth extends MethodGroup  
	{
		public function Auth(service:ServiceBase)
			{
			super(service);
		}
		
		private var lastPassword:String
		private var lastUsername:String
		public function login(username:String, password:String, hashpassword:Boolean = true):void
		{
		 	lastPassword = password;
		 	lastUsername = username;
		 	
		 	
		 	var md5pass:String  = hashpassword ? MD5.hash(username + password) : password;
		 	trace("login ..");
			MethodGroupHelper.invokeMethod(service, onLogin, "login/auth", {username:username, password:md5pass})
		}
		
		 
		private function onLogin(e:Event):void
		{
			
			if(isError(e, SeesmicResultEvent.AUTH_LOGIN, "login"))
			{
				return;
				
				
			}
			
		 
			var object:Object = parse(e.target);
			
			 
			var sid:String = object.login.sid
			var session_id:String  = object.login.session_id;
			
			
			var sv:SeesmicService = service as SeesmicService
			sv.password  = lastPassword
			sv.username = lastUsername
			
			this.dispatchEvent(new SeesmicResultEvent(SeesmicResultEvent.AUTH_LOGIN, {success:(object.login.success == "true"), sid:sid, session_id:session_id}))
			service.dispatchEvent(new SeesmicResultEvent(SeesmicResultEvent.AUTH_LOGIN, {success:(object.login.success == "true"), sid:sid, session_id:session_id}));
			
			 
		}
		
		public function logout():void
		{
			MethodGroupHelper.invokeMethod(service, onLogout, "login")
		}
		
		private function onLogout(e:Event):void
		{
			//var loader:URLLoader = e.target as URLLoader
			//var jsonString:String = String(loader.data)
			//var object:Object = JSON.deserialize(jsonString)
			//trace(object)
			this.dispatchEvent(new SeesmicResultEvent(SeesmicResultEvent.AUTH_LOGOUT, null))
			
			service.dispatchEvent(new SeesmicResultEvent(SeesmicResultEvent.AUTH_LOGOUT, null))
		}

	}
}